import { useEffect, useState } from 'react'
import styles from './Sidebar.module.scss'

interface Heading {
  id: string
  text: string
  level: number
}

interface SidebarProps {
  content: string
}

function Sidebar({ content }: SidebarProps) {
  const [headings, setHeadings] = useState<Heading[]>([])

  const cleanText = (text: string) => {
    return text
      .replace(/[\p{P}\p{S}]/gu, '') // 移除所有中英文标点符号
      .replace(/\s+/g, '-')
      .toLowerCase()
  }

  useEffect(() => {
    const headingRegex = /^(#{1,6})\s+(.+)/gm
    const extractedHeadings: Heading[] = []
    let match

    while ((match = headingRegex.exec(content)) !== null) {
      const level = match[1].length
      const text = match[2].trim()
      const id = cleanText(text)
      extractedHeadings.push({ id, text, level })
    }

    setHeadings(extractedHeadings)
  }, [content])

  return (
    <div className={styles.sidebar}>
      <h2 className={styles.sidebarTitle}>目录</h2>
      <ul className={styles.sidebarList}>
        {headings.map((heading) => (
          <li
            key={heading.id}
            className={styles.sidebarItem}
            style={{ marginLeft: `${(heading.level - 1) * 16}px` }}
          >
            <a href={`#${heading.id}`} className={styles.sidebarLink}>
              {heading.text}
            </a>
          </li>
        ))}
      </ul>
    </div>
  )
}

export default Sidebar
